package me.lc.filarSocksUniform.util;

import java.text.DecimalFormat;
import java.util.HashMap;

import me.lc.filarSocksUniform.GirlGalleryActivity;
import me.lc.filarSocksUniform.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class GalleryAdapter extends BaseAdapter {

	int girlIndex;
	HashMap<Integer, ImageView> images = new HashMap<Integer, ImageView>();
	HashMap<Integer, Bitmap> bitmaps = new HashMap<Integer, Bitmap>();
	GirlGalleryActivity context;
	DisplayMetrics dm;
	int inSampleSize = 1;

	public GalleryAdapter(int index, GirlGalleryActivity context) {
		girlIndex = index;
		this.context = context;
		dm = new DisplayMetrics();
		(context).getWindowManager().getDefaultDisplay().getMetrics(dm);

		double temp = 480.0 / dm.widthPixels;
		if (temp > 1) {
			inSampleSize = 2;
		}
	}

	public void recycle() {
		for (int i = 0; i < ResourceManager.indexToCountMap.get(girlIndex); i++) {
			if (images.containsKey(i)) {
				ImageView v = images.get(i);
				if (v != null) {
					v.setImageResource(R.drawable.icon);
				}
			}
			if (bitmaps.containsKey(i)) {
				bitmaps.get(i).recycle();
			}
		}
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return ResourceManager.indexToCountMap.get(girlIndex);
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (images.containsKey(position)) {
			return images.get(position);
		}
		ImageView img = new ImageView(context);
		img.setScaleType(ImageView.ScaleType.FIT_CENTER);
		String preName = ResourceManager.indexToResPreMap.get(girlIndex);
		DecimalFormat format = new DecimalFormat("00");
		int imgId = context.getResources().getIdentifier(
				preName + "_" + format.format(position + 1), "drawable",
				context.getPackageName());
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inSampleSize = inSampleSize;
			Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
					imgId, opts);
			bitmaps.put(position, bmp);
			img.setImageBitmap(bmp);
		} catch (OutOfMemoryError err) {
		}

		img.setImageResource(imgId);
		images.put(position, img);
		return img;
	}
}
